// pages/repairRecord/repairRecord.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import util from '../../utils/util.js';
import Base64 from '../../utils/Base64.js';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //删除确认框
    showDelete:false,
    //传参来的设备id
    equipmentId:null,
    //传参来的设备编码
    equipmentNo:null,
    //状态筛选
    option: [
      { text: '所有记录', value: 3 },
      { text: '未处理', value: 0 },
      { text: '处理中', value: 1 },
      { text: '已完成', value: 2 }
    ],
    value: 3,
    //当前登录用户
    user:{},
    //设备维修明细
    showDetail:false,
    //处理过程详情
    afterSaleObj:{},
    //处理过程-设备编号
    detailTitle:'',
    //删除的设备编号
    deleteEquipmentId:null,
    //用户权限
    authority:null,
    //搜索词
    searchValue:'',
    //通话记录弹出层
    showCallRecord:false,
    //通话记录信息
    callRecordInfo:null,
    //避免表单重复提交
    code:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;

    //当前登录用户
		this.setData({
      user: user,
      authority:app.globalData.authority,
      code:Base64.encode(new Date() + user.userName),
    })

    if(options.equipmentId && options.equipmentNo){
      this.setData({
        equipmentId: parseInt(options.equipmentId),
        equipmentNo: options.equipmentNo
      })
    }

    //查询字典-处理方式
    this.getAfterSaleMethod();

    //查询字典-故障类型
    this.getAfterSaleType();

    //获取报修列表
    this.getList();
  },

  //获取报修列表
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let param={
      isAuth:true,
      className:'afterRepairRecord',
      data:{
        selectFields: ["id","equipmentId","equipmentNo","state","departId","remark","pic","contactPerson","departObj","repairTime","contact","callRecord","dataAuthority","address","projectObj","afterSaleObj","businessType"],
        sort:{
          repairTime:-1
        },
        "page": {
          "page": this.data.page,
          "pageSize": 10
        }
      }
    }

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        param.data.appId=app.globalData.myAppId;
      }else{
        param.data.appId=[2,3,null];
      }
    }else{
      param.data.appId=[2,3,null];
    }

    //查某一台设备的记录
    if(this.data.equipmentNo){
      param.data.equipmentNo=this.data.equipmentNo;
    }

    //搜索-编码模糊查询
    if(this.data.searchValue){
      param.data.equipmentNo='%'+this.data.searchValue+'%';
    }

    //筛选状态
    if(this.data.value!=3){
      param.data.state=this.data.value;
    }  

    CommonService.goFindList(param).then(res=>{
      Toast.clear();
      if(res.data.data && res.data.data.result){
        let result=res.data.data.result;
        if(result.length){
          for(let i=0;i<result.length;i++){
             //处理状态
             switch(result[i].state){
              case 0:
                result[i].stateWord='未处理';
                result[i].stateClass='c-3';
                break;
              case 1:
                result[i].stateWord='处理中';
                result[i].stateClass='c-1';
                break;
              case 2:
                result[i].stateWord='已完成';
                result[i].stateClass='c-2';
                break;
            }

            //处理图片
            if((result[i].pic) && (result[i].pic!='null') && (result[i].pic!='[]')){
              result[i].pics=JSON.parse(result[i].pic);
            }

            //处理时间
            if(result[i].repairTime){
              result[i].repairTime=util.timeFormat(result[i].repairTime);
            }

            if(result[i].afterSaleObj && result[i].afterSaleObj.length && result[i].afterSaleObj[0].processingTime){
              result[i].afterSaleObj[0].processingTime=util.timeFormat(result[i].afterSaleObj[0].processingTime);
            }

            if(result[i].afterSaleObj && result[i].afterSaleObj.length && result[i].afterSaleObj[0].processingEndTime){
              result[i].afterSaleObj[0].processingEndTime=util.timeFormat(result[i].afterSaleObj[0].processingEndTime);
            }
          }

          console.log('设备报修列表');
          console.log(result);

          this.setData({
            list: this.data.list.concat(result)
          });
        }else{
          this.setData({
            notMore: false
          })
          if(this.data.page==1){
            this.setData({
              showNothing: true
            });
          }else{
            Toast.fail('没有更多了');
          }
        }
      }else{
        if(this.data.page==1){
          this.setData({
            showNothing: true
          });
        }
      }
    }).catch((error) => {
      Toast.clear();
      this.setData({
        showNothing: true
      });
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //跳转添加
  goToAdd(){
    if(this.data.equipmentId){
      wx.navigateTo({
        url: "/pages/repairAdd/repairAdd?equipmentId="+this.data.equipmentId
      })
    }else{
      wx.navigateTo({
        url: "/pages/repairAdd/repairAdd"
      })
    }
  },

  //显示删除确认框
  onDelete(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({
      showDelete: true,
      deleteId:detail.id,
      deleteEquipmentId:detail.equipmentId
		})
  },

  //隐藏删除确认框
  onCloseDelete(){
    this.setData({
			showDelete: false
		})
  },

  //确认删除
  confirmDelete(){
    let param={
      className:"repairRecord",
      data:{
        id:this.data.deleteId
      }
    }

    CommonService.goDelete(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        //查询是否还有报修
        this.lookState();
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //查询是否还有报修
  lookState(){
    let param={
      isAuth:false,
      className:'afterRepairRecord',
      data:{
        selectFields:['id'],
        equipmentId:this.data.deleteEquipmentId,
        state:{"!=":2}
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data.count){
        //刷新列表和页码
        this.refreshListAndPage();
      }else{
        //更新设备状态
        this.updateState();
      }
    }).catch((error) => {
    })
  },

  //更新设备状态
  updateState(){
    let param={
      className:'equipment',
      data:{
        filter: {
          id:this.data.deleteEquipmentId
        },
        update: {
          set: {
            state:0
          }
        }
      }
    }

    CommonService.goUpdate(param).then(res=>{
      //刷新列表和页码
      this.refreshListAndPage();
    }).catch((error) => {
    })
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;

    let newArr=[];
    for(let i=0;i<detail.length;i++){
      newArr.push(detail[i].url);
    }

    wx.previewImage({
      current: src,
      urls: newArr
    })
  },

  //选择状态
  onChange({detail}) {
    this.setData({
      value: detail
    })
    this.refreshListAndPage();
  },

  //显示处理过程明细
  onShowDetail(e){
    let detail = e.target.dataset.detail;
    let afterSaleObj=detail.afterSaleObj[0];

    let methodMap=this.data.methodMap;
    let faultMap=this.data.faultMap;

    //console.log(afterSaleObj,methodMap,faultMap);

    methodMap.forEach(function(value,key){
　　  if(key==afterSaleObj.method){
        afterSaleObj.methodStr=value;
      }
　　});

    faultMap.forEach(function(value,key){
　　  if(key==afterSaleObj.faultType){
        afterSaleObj.typeStr=value;
      }
　　});

    this.setData({
      showDetail: true,
      detailTitle:detail.equipmentNo,
      afterSaleObj:afterSaleObj
    })
  },

  //隐藏处理过程明细
  onCloseDetail(){
    this.setData({
			showDetail: false
		});
  },

  //维修接待
  onReceive(e){
    Dialog.confirm({
      title: '维修接待',
      message: '确定接单吗？',
    }).then(() => {
      //避免表单重复提交
      Toast.loading({
        duration: 0,
        forbidClick: true,
        message: '数据提交中...'
      });

      let detail=e.currentTarget.dataset.detail;
      let user=app.globalData.userInfo;

      //权限
      let authDepart=detail.dataAuthority.depart;
      authDepart.push(user.departObj[0].companyId,user.depart);
      let arrSet=new Set(authDepart);
      authDepart=Array.from(arrSet);

      let param={
        repairId:detail.id,
        equipmentId:detail.equipmentId,
        equipmentNo: detail.equipmentNo,
        departId: detail.departId,
        projectId: detail.projectId,
        user:{
          id:user.id,
          name:user.userName,
          phone:user.personalPhone,
        },
        dataAuthority: {
          depart:authDepart
        },
        appId: [app.globalData.myAppId],
        businessType: detail.businessType
      }

      //console.log(param);
      
      CommonService.maintenanceReception(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.clear();
          Dialog.confirm({
            title: '接待成功',
            confirmButtonText:'查看工单',
            cancelButtonText:'留在本页'
          }).then(() => {
            //跳转到售后记录
            wx.reLaunch({
              url: '/pages/afterSalesList/afterSalesList'
            })
          }).catch(() => {
            //刷新列表和页码
            this.refreshListAndPage();
          });

        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    })
  },

  //点击拨打电话
  onCall(e){
    let userName=app.globalData.userInfo.userName;
    let detail=e.currentTarget.dataset.detail;    

    //打电话
    wx.makePhoneCall({
      phoneNumber: detail.contact
    })

    //保存点击记录
    let callRecord=[];
    if(detail.callRecord && detail.callRecord.length){
      callRecord=detail.callRecord;
    }
    callRecord.push({
      time:util.timeFormat(new Date()),
      name:userName
    });

    //售后服务记录
    let serviceDetails=[];
    let afterId=null;
    if(detail.afterSaleObj && detail.afterSaleObj.length){
      afterId=detail.afterSaleObj[0].id;
      if(detail.afterSaleObj[0].serviceDetails && detail.afterSaleObj[0].serviceDetails.length){
        serviceDetails=detail.afterSaleObj[0].serviceDetails;
      }
    }
    serviceDetails.push({
      content: userName + " 拨打了电话",
      datetime: util.timeFormat(new Date())
    });

    let param={
      className:'afterRepairRecord',
      data:{
        id:detail.id,
        callRecord:callRecord
      }
    }
    CommonService.goSave(param).then(res=>{
      if(afterId){
        //售后记录增加详情
        this.insertAfterDetail(afterId,serviceDetails);
      }

      //刷新列表和页码
      this.refreshListAndPage();

    }).catch((error) => {
    })
  },

  //搜索输入时
  onChangeSearch(e){
    this.setData({
      searchValue: e.detail.value
    })
  },

  //点击搜索
  onSearch() {
    //刷新列表和页码
    this.refreshListAndPage();
  },

  //显示通话记录
  onShowCallRecord(e){
    let detail=e.currentTarget.dataset.detail;

    let param={
      isAuth:false,
      className:'afterRepairRecord',
      data:{
        searchAll: true,
        id:detail.id,
        selectFields:['id','equipmentNo','repairTime','callRecord']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result.length){
        let result=res.data.data.result[0];
        if(result.callRecord && result.callRecord.length){
          result.repairTime=util.timeFormat(result.repairTime);
          this.setData({
            showCallRecord: true,
            callRecordInfo:result
          })
        }else{
          Toast.fail('暂无通话记录')
        }
      }else{
        Toast.fail('暂无通话记录')
      }
    }).catch((error) => {
      Toast.fail('暂无通话记录')
    })
  },

  //隐藏通话记录
  onCloseCallRecord(){
    this.setData({
      showCallRecord: false
    })
  },

  //查询字典-处理方式
  getAfterSaleMethod(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'processMode',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let map = new Map();

        result.forEach(item => {
          map.set(item.id,item.name);
        });

        this.setData({
          methodMap: map
        })
      }
    }).catch((error) => {
    })
  },

  //查询字典-故障类型
  getAfterSaleType(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'faultType',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let map = new Map();

        result.forEach(item => {
          map.set(item.id,item.name);
        });

        this.setData({
          faultMap: map
        })
      }
    }).catch((error) => {
    })
  },

  //售后记录增加详情
  insertAfterDetail(id,arr){
    let param={
      className:'afterSaleServiceRecord',
      data:{
        id:id,
        serviceDetails:arr
      }
    }

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})
